import React, { useState,useEffect } from 'react';  
import { Card, Button, Table, Modal, Form, Input,Tooltip,List, Select, message } from 'antd';  
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined } from '@ant-design/icons'; 
import { list} from "@/api/modules/inci";
import { listSarm,getSarm,delSarm,addSarm,updateSarm} from "@/api/modules/jnj/rm";
const { Option } = Select;  
// 假设你有一些初始数据  
const initialData = []; // 你可以根据需要填充这些数据  
  
const RMDetail = ({oldid,onUploadSuccess}) => {  
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [visible, setVisible] = useState(false);  
  const [formData, setFormData] = useState({});  
  const [inciData, setInciData] = useState(initialData); // INCI 表格数据  
  const [phraseData, setPhraseData] = useState([]); // 话术表格数据  
  const [form] = Form.useForm();  
  const [inciform] = Form.useForm();
  const [isView, SetisView] = useState(false)
  // 假设的添加话术行的函数  
  const addPhraseRow = () => {  
    setPhraseData([...phraseData, { id: -Date.now(),key:Date.now(), productType: '淋洗',wordingCn:'',wordingEn:'', }]);  

  };  
  useEffect(() => {  
        const data = oldid
        form.setFieldsValue(data)
        for(let i =0;i<data.safetyRmWordingList.length;i++){
          data.safetyRmWordingList[i].id = -i
        }
        for(let i =0;i<data.rmInciList.length;i++){
          data.rmInciList[i].id = -i
        }
        data.rmInciList.map(i=>{
          if(i.inci == undefined || i.inci == null || i.inci ==''){
            //
          }else{
            i.inciCn=i.inci.inciCn
            i.inciUs=i.inci.inciUs
          }
       
        })
        setPhraseData(data.safetyRmWordingList)
        setInciData(data.rmInciList)
  }, []); 

  const handleINCIOk = () => { 
      let data = inciform.getFieldsValue()
      let idx = 0
      console.log(inciData,'inciData')
      console.log(data,'data')
      if(inciData.length==0){
        setInciData([...inciData,{id: -Date.now(),key:Date.now(),lawInciSerial:data.lawInciSerial,inciCn:data.inciCn,inciUs:data.inciUs,mainSupplement:data.mainSupplement,percentage:data.percentage,percentageRange:data.percentageRange,processType:data.processType,seq:data.seq,function1:data.function1,remark:data.remark}])
        setVisible(false)
      }else{
        inciData.map(i=>{
          if(i.id == data.id){
            idx=1
          }
        })
        if(idx==1){
          const updatedInciData = inciData.map(item => {  
            // 如果找到了匹配的id，返回合并后的新对象  
            if (item.id === data.id) {  
              return {  
                ...data, // 假设data只包含需要更新的字段  
                id: item.id, // 如果id是自动生成的，并且你不想改变它，保持原来的id  
                // 如果还有其他不需要改变的字段，也可以在这里明确指定  
              };  
            }  
            // 如果没有找到匹配的id，返回原始对象  
            return item;  
          });  
          
          setInciData(updatedInciData);  
          setVisible(false);
        }
        if(idx==0){
          setInciData([...inciData,{id: -Date.now(),key:Date.now(),lawInciSerial:data.lawInciSerial,inciCn:data.inciCn,inciUs:data.inciUs,mainSupplement:data.mainSupplement,percentage:data.percentage,percentageRange:data.percentageRange,processType:data.processType,seq:data.seq,function1:data.function1,remark:data.remark}])
          setVisible(false)
        }
      }
   }
  
  // 假设的表单提交函数（这里只是更新state）  
  const handleSubmit = (values) => {  
    // 根据需要处理表单提交，可能是发送到服务器  
    setVisible(false);  
    // 对于INCI，你可能需要更新inciData  
    // 对于话术，你可能需要更新phraseData的某一行  
  };  
  
  // 渲染表格列  
  const columnsInci : any = [
    {
      title: t('inci.serial'),
      dataIndex: 'lawInciSerial',
      key: 'lawInciSerial',
      width: 80,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (lawInciSerial) => (
        <Tooltip placement="topLeft" title={lawInciSerial}>
          {lawInciSerial}
        </Tooltip>
      ),
    },

    {
      title: t('inci.inciCn'),
      dataIndex: 'inciCn',
      width: 80,
      key: 'inciCn',
      ellipsis: {
        showTitle: false,
      },
      render: (inciCn) => (
        <Tooltip placement="topLeft" title={inciCn}>
          {inciCn}
        </Tooltip>
      ),
    },
    {
      title: t('inci.inciUs'),
      dataIndex: 'inciUs',
      width: 120,
      key: 'inciUs',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sarm.mainSupplement'),
      dataIndex: 'mainSupplement',
      width: 80,
      key: 'mainSupplement',
      ellipsis: {
        showTitle: false,
      },
      render: (mainSupplement) => (
        <Tooltip placement="topLeft" title={mainSupplement}>
          {mainSupplement}
        </Tooltip>
      ),
    },
    {
      title: t('percentage'),
      dataIndex: 'percentage',
      key: 'percentage',
      ellipsis: {
        showTitle: false,
      },
      render: (percentage) => (
        <Tooltip placement="topLeft" title={percentage}>
          {percentage}
        </Tooltip>
      ),
    },
    {
      title: t('sarm.percentageRange'),
      dataIndex: 'percentageRange',
      key: 'percentageRange',
      ellipsis: {
        showTitle: false,
      },
      render: (percentageRange) => (
        <Tooltip placement="topLeft" title={percentageRange}>
          {percentageRange}
        </Tooltip>
      ),
    },
    {
      title: t('sarm.processType'),
      dataIndex: 'processType',
      key: 'processType',
      width:120,
      ellipsis: {
        showTitle: false,
      },
      render: (processType) => (
        <Tooltip placement="topLeft" title={processType}>
          {processType}
        </Tooltip>
      ),
    },
    {
      title: t('sarm.seq'),
      dataIndex: 'seq',
      key: 'seq',
      ellipsis: {
        showTitle: false,
      },
      render: (seq) => (
        <Tooltip placement="topLeft" title={seq}>
          {seq}
        </Tooltip>
      ),
    },
    {
      title: t('sarm.incifunction1'),
      dataIndex: 'function1',
      key: 'function1',
      ellipsis: {
        showTitle: false,
      },
      render: (function1) => (
        <Tooltip placement="topLeft" title={function1}>
          {function1}
        </Tooltip>
      ),
    },
    {
      title: t('sarm.remark'),
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: {
        showTitle: false,
      },
      render: (remark) => (
        <Tooltip placement="topLeft" title={remark}>
          {remark}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      width:100,
      render: (text, record) => (  
        <>  
          <Button disabled={isView} type="link" onClick={() => handleEdit(record)}>  
          {t('edit')}  
          </Button>  
          <Button disabled={isView} type="link" danger onClick={() => handleDelete(record.id)}>  
          {t('delete')}   
          </Button>  
   
        </>  
      ),  
    },  
  ];

  const handleEdit = (record) =>{
    inciform.resetFields()
    inciform.setFieldsValue(record)
    setVisible(true)
  }

  const handleDelete = (id) =>{
    setInciData(inciData.filter((row) => row.id !== id));  
  }
  
  const columnsPhrase = [  
    {  
      title: t('rmwording.productType'),  
      dataIndex: 'productType',  
      key: 'productType',  
      render: (_, record) => (  
        <select 
        style={{width:'100%'}}
        value={record.productType}  
        onChange={(e) => handleSelectChange(e.target.value, record.id)}  
      >  
        <option value="淋洗">淋洗</option>  
        <option value="驻留">驻留</option>  
      </select> 
      ),  
    },  
    // ...其他列  
    {  
      title: t('rmwording.wordingCn'),  
      dataIndex: 'wordingCn',  
      key: 'wordingCn',  
      render: (_, record) => (  
        <Input.TextArea value={record.wordingCn} onChange={(e) => handlePhraseChange(e.target.value,'wordingCn', record.id)} />  
      ),  
    },  
    {  
      title: t('rmwording.wordingEn'),  
      dataIndex: 'wordingEn',  
      key: 'wordingEn',  
      render: (_, record) => (  
        <Input.TextArea value={record.wordingEn} onChange={(e) => handlePhraseChange(e.target.value,'wordingEn', record.id)} />  
      ),  
    },  
    {  
      title: t('action'),  
      key: 'action',  
      render: (_, record) => (  
        <Button type="link" disabled={isView} onClick={() => deletePhraseRow(record.id)}>  
          {t('delete')}  
        </Button>  
      ),  
    }, 
  ];  

  const deletePhraseRow = (id) =>{
    setPhraseData(phraseData.filter((row) => row.id !== id));  
  }

  const handleSelectChange = (value, id) => {  
    setPhraseData(  
      phraseData.map((row) => {  
        if (row.id === id) {  
          return { ...row, productType: value };  
        }  
        return row;  
      })  
    );  
  };  
  
  // 假设的处理话术内容变化函数  
  const handlePhraseChange = (value,type, id) => { 
    setPhraseData(  
      phraseData.map((row) => {  
        if (row.id === id) {  
          return { ...row,[type] : value };  
        }  
        return row;  
      })  
    );  
  };  

  //select查询

  const [searchResult, setSearchResult] = useState([]);  
  const [incivisible, setINCIVisible] = useState(false);  
  const [selectedResult, setSelectedResult] = useState(null);  
  
  const handleSearch = (values) => {  
    // 假设这里有一个异步的搜索函数，它返回搜索结果  
    const fakeSearch = async () => {  
      const inci = inciform.getFieldsValue()
      const data={
        page:1,
        limit:999,
        search:inci.inciStr,
        orderby:'id',
    }
    list(data).then(res=>{
        let incis=res.data.data.page
        incis.map(item=>{
          item.name=(item.inciCn?''+item.inciCn:'') + (item.inciUs?' ,'+item.inciUs:'')
        })
        setSearchResult(incis);
        setINCIVisible(true);  
    })
    };  
    fakeSearch()
  };  

  const handleSelectResult = (result) => {  
    inciform.setFieldsValue({ inciStr: result.name }); // 回填表单  
    inciform.setFieldsValue({lawInciSerial:result.serial})
    inciform.setFieldsValue({inciCn:result.inciCn})
    inciform.setFieldsValue({inciUs:result.inciUs})
    inciform.setFieldsValue({ingredient:result.inciUs})
    inciform.setFieldsValue({ingredientName:result.inciUs})
    setSelectedResult(result);  
    setINCIVisible(false); // 关闭弹窗  
  };  

    
  const modalFooter = [  
    <Button key="back" onClick={() => setINCIVisible(false)}>  
      {t('cancel')}  
    </Button>,  
    
  ];  

  // 渲染Modal表单  
  const modalContent = (  
    <Form form={inciform} layout="vertical">  
      {/* ...你的表单项 */}  
      <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
      </Form.Item> 
      <Form.Item name="inciStr" label="INCI">  
        <Input />  
      </Form.Item>  
      <Form.Item>  
        <Button type="primary" htmlType="submit" onClick={handleSearch}>  
           INCI搜索  
        </Button>  
      </Form.Item> 
      <Modal  
        title="Result"  
        visible={incivisible}  
        onCancel={() => setINCIVisible(false)}  
        footer={modalFooter}  
      >  
        <List  
          itemLayout="horizontal"  
          dataSource={searchResult}  
          renderItem={(item) => (  
            <List.Item  
              actions={[  
                <Button type="link" onClick={() => handleSelectResult(item)}>  
                  选择  
                </Button>,  
              ]}  
            >  
              <List.Item.Meta  
                title={<span>{item.name}</span>}  
              />  
            </List.Item>  
          )}  
        />  
      </Modal>  
      <Form.Item name="lawInciSerial" label={t('inci.serial')}>  
        <Input disabled/>  
      </Form.Item>
      <Form.Item name="inciCn" label={t('inci.inciCn')}>  
        <Input disabled/>  
      </Form.Item> 
      <Form.Item name="inciUs" label={t('inci.inciUs')}>  
        <Input disabled/>  
      </Form.Item> 
      <Form.Item name="mainSupplement" label={t('sarm.mainSupplement')}>  
        <Select>
          <Option value="Y">Y</Option>  
          <Option value="N">N</Option>  
        </Select>  
      </Form.Item>
      <Form.Item name="percentage" label={t('percentage')}>  
        <Input/>  
      </Form.Item> 
      <Form.Item name="percentageRange" label={t('sarm.percentageRange')}>  
        <Input/>  
      </Form.Item> 
      <Form.Item name="processType" label={t('sarm.processType')}>  
        <Input/>  
      </Form.Item> 
      <Form.Item name="seq" label={t('sarm.seq')}>  
        <Input/>  
      </Form.Item> 
      <Form.Item name="function1" label={t('sarm.function1')}>  
        <Input/>  
      </Form.Item> 
      <Form.Item name="remark" label={t('sarm.remark')}>  
        <Input/>  
      </Form.Item> 
    </Form>  
  );  

  const CustomTitleWithButton = ({ title, onClick }) => (  
    <div style={{ display: 'flex', alignItems: 'center' }}>  
      <span>{title}</span>  
      <Button style={{ marginLeft: '8px' }} onClick={submitFormCancel}>  
        {t('cancel')}  
      </Button>  
    </div>  
  ); 
  const submitFormCancel = () =>{
      onUploadSuccess('cancel','')
  }

  const getQueryVariable = (variable) =>{
    const query = window.location.search.substring(1);
    const vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
  }

  const submitForm = () =>{
    let data = form.getFieldsValue()
    data.safetyRmWordingList = phraseData
    data.safetyRmInciList = inciData
    onUploadSuccess('ok',data)

  }

  const handleADDINCI = () =>{
    inciform.resetFields()
    setVisible(true)
  }

  
  return (  
    <div>  
      <Card title={  
          <CustomTitleWithButton  
        title={t('report.basicInformation')}  
        onClick={submitFormCancel}
      />  
    }

      >  
        {/* 这里放置你的表单 */} 
        <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="rmNumber"  
              label={t('sarm.rmNumber')}
              rules={[{ required: true, message: '请输入原料编码！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="rmName"  
              label={t('sarm.rmName')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="commercialName"  
              label={t('sarm.commercialName')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="singlePl"  
              label={t('sarm.singlePl')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="manufactureName"  
              label={t('sarm.manufactureName')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="distributorName"  
              label={t('sarm.distributorName')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="remark"  
              label={t('sarm.remark')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="function1"  
              label={t('sarm.function1')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
          </Form>   
      </Card>  
      <Card style={{marginTop:'2%'}} title={<strong>INCI</strong>}>  
        <Button disabled={isView} type="primary" onClick={() => handleADDINCI()}>  
          {t('add')}  
        </Button>  
        <Table style={{marginTop:'2%'}} columns={columnsInci} dataSource={inciData} pagination={false}/>  
        <Modal title="INCI" visible={visible}  onCancel={() => setVisible(false)}  onOk={handleINCIOk} destroyOnClose>  
          {modalContent}  
        </Modal>    
      </Card>  
      <Card style={{marginTop:'2%'}} title={<strong>{t('wording')}</strong>}>  
        <Button disabled={isView} type="primary" onClick={addPhraseRow}>  
          {t('add')}  
        </Button>  
        <Table style={{marginTop:'2%'}} columns={columnsPhrase} dataSource={phraseData} pagination={false}/>  
      </Card>
       {/* 在这里放置保存按钮 */}  
       <div style={{ textAlign: 'left', marginTop: '16px' }}>  
                <Button type="primary" disabled={isView} onClick={() => { submitForm() }}>  
                  {t('save')}  
                </Button>  
                <Button style={{marginLeft:'2%'}} onClick={() => { submitFormCancel() }}>  
                  {t('cancel')}  
                </Button> 
           </div>   
    </div>  
  );  
};  
  
export default RMDetail;